﻿using StuClassInfo;
using StuClassInfo.StuCommon;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace StuClassInfo
{
    public partial class UpdateStu : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                info();
                ddlClass();
            }
        }

        #region 绑定班级
        private void ddlClass()
        {
            ////1.实例化
            //var db = new StuUseEntities();
            //var model = db.UserInfo.FirstOrDefault(s => true);
            ////dd_class.DataTextField = model.StuClass.classname;
            ////dd_class.DataValueField = model.StuClass.classid.ToString();
            //dd_class.SelectedValue = model.StuClass.classid.ToString();

            string sql = "SELECT * FROM dbo.StuClass";
            DataTable table = Dbhelper.datatable(sql);
            dd_class.DataSource = table;
            dd_class.DataTextField = "classname";
            dd_class.DataValueField = "classid";
            dd_class.DataBind();
            dd_class.Items.Insert(0, new ListItem("不限", "0"));


        }
        #endregion


        #region 显示修改的信息
        /// <summary>
        ///显示修改的信息
        /// </summary>
        private void info()
        {
            //接受要修改的id
            int stuid = Convert.ToInt32(Request.QueryString["userid"]);
            //1.实例化
            var db = new StuUseEntities();
            var model = db.UserInfo.FirstOrDefault(s => s.userid == stuid);
            if (model != null)
            {
                txt_name.Text = model.username;
                txt_age.Text = model.userage.ToString();
                txt_phone.Text = model.userphone;
                txt_email.Text = model.userEmail;
                dd_class.SelectedValue = model.classid.ToString(); ;
            }
        }
        #endregion


        private void Update()
        {
            //接受要修改的id
            int stuid = Convert.ToInt32(Request.QueryString["userid"]);
            //1.实例化
            var db = new StuUseEntities();
            var model = db.UserInfo.FirstOrDefault(s => s.userid == stuid);
            if (model != null)
            {
                model.username = txt_name.Text;
                model.userage = Convert.ToInt32(txt_age.Text);
                model.userphone = txt_phone.Text;
                model.userEmail = txt_email.Text;
                model.classid = Convert.ToInt32(dd_class.SelectedValue);
            }
            if (db.SaveChanges() > 0)
            {
                JSHelper.Alert(this, "修改成功", "StuInfo.aspx");
            }
            else
            {
                lbl_msg.Text = "修改失败！";
            }
        }

        protected void btn_submit_Click(object sender, EventArgs e)
        {
            Update();
        }
    }
}